package nk.stack;

import java.util.LinkedList;

public class AB2 {


    public boolean IsPopOrder (int[] pushV, int[] popV) {
        LinkedList<Integer> stack = new LinkedList<>();
        int i = 0, j = 0;
        if (pushV.length != popV.length)
            return false;

        while ((i < pushV.length || !stack.isEmpty()) && j < popV.length) {
            if (i < pushV.length ) {
                if (pushV[i] == popV[j]) {
                    i++; j++;
                } else {
                    if (stack.isEmpty() || stack.peek() != popV[j]) {
                        stack.push(pushV[i]);
                        i++;
                    } else {
                        stack.pop();
                        j++;
                    }
                }
            } else {
                if (stack.isEmpty() || stack.peek() != popV[j])
                    return false;
                stack.pop();
                j++;
            }
        }
        if (j == popV.length)
            return true;
        return false;
    }


    public static void main(String[] args) {
        AB2 ab2 = new AB2();
        int[] a = {1,2,3,4,5};
        int[] b = {4,5,3,2,1};
        System.out.println(ab2.IsPopOrder(a,b));
    }

}
